package com.shop.page.controller;

import com.shop.common.entity.CommonResult;
import com.shop.common.pojo.Product;
import com.shop.page.service.ProductService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.util.List;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-11-03
 */
@RestController
@RequestMapping("/pages")
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    Configuration configuration;

    //页面输出的路径
    @Value("${pagepath}")
    private String pagePath;

    @GetMapping("/generate")
    public CommonResult generate() {
        FileWriter out = null;
        try {
            List<Product> list = productService.findAllWithPdesc();

            for (Product product : list) {
                //获取模板
                Template template = configuration.getTemplate("introduction.ftl");
                //获取输出流
                out = new FileWriter(pagePath + product.getId() + ".html");
                //D:\2004\idea_code\four\shop-parent\shop-common-service\shop-page-service\src\main\resources\static\\3.html
                //输出页面
                template.process(product, out);
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new CommonResult("静态页面生成OK");
    }


}
